<template>
  <div>
    <el-dialog
      :title="keyword+'爬取的产品列表'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      class="mt-dialog"
      width="80%"
      @close="close"
    >

      <div class="top">
        <el-row style="margin-bottom: 5px;">
          <el-col :xs="24" :sm="12" :md="12" :lg="5" :xl="5">
            <el-select
              v-model="direct_upload_web_id"
              filterable
              clearable
              placeholder="选择直接上传的网站"
              @change="handleDirectUPloadChange"
            >
              <el-option
                v-for="item in websites"
                :key="item.id"
                :label="item.domain"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="5" :xl="5">
            <el-select v-model="uploadedonly" placeholder="请选择" @change="getList">
              <el-option
                v-for="item in uploadedonlyoptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="5" :xl="5">
            <el-select v-model="product_type" clearable placeholder="请选择" @change="getList">
              <el-option
                v-for="item in product_types"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="9" :xl="9">
            <el-button
              v-if="direct_upload_web_id"
              size="mini"
              :type="direct_upload_state"
              @click.native.stop="handleCHooseDirectuploadCategory()"
            >配置目录
            </el-button>
            <el-button
              v-if="direct_upload_web_id && multipleSelection.length"
              size="mini"
              type="primary"
              @click.native.stop="handleClickDirectUpload()"
            >上传选择
            </el-button>
            <el-button
              v-if="multipleSelection.length"
              size="mini"
              type="success"
              @click.native.stop="handleBatchRemoveBg()"
            >一键去水印
            </el-button>
            <el-button
              v-if="direct_upload_web_id"
              size="mini"
              type="primary"
              @click.native.stop="handleClickDirectUploadAll()"
            >批量上传
            </el-button>
          </el-col>
        </el-row>

        <el-row>
          <div style="display: inline-block;background-color: #0a76a4" :hidden="true">
            <el-row style="margin: 5px" :gutter="10">
              <el-col :span="5">
                <el-input v-model="min_orders" size="mini" placeholder="0">
                  <template slot="prepend">最低订单</template>
                </el-input>
              </el-col>
              <el-col :span="5">
                <el-input v-model="min_price" size="mini" placeholder="0">
                  <template slot="prepend">最低价格</template>
                </el-input>
              </el-col>
              <el-col :span="5">
                <el-input v-model="max_price" size="mini" placeholder="0">
                  <template slot="prepend">最高价格</template>
                </el-input>
              </el-col>
              <el-col :span="5">
                <el-input v-model="min_reviews" size="mini" placeholder="0">
                  <template slot="prepend">最低reviews</template>
                </el-input>
              </el-col>
              <el-col :span="4">
                <el-input v-model="min_star" size="mini" placeholder="0">
                  <template slot="prepend">评分</template>
                </el-input>
              </el-col>
            </el-row>
            <el-row style="margin: 5px">
              <el-col :span="24">
                <el-input v-model="kwInput" size="mini" placeholder="输入任意字符 进行筛选">
                  <el-button slot="append" icon="el-icon-search" @click="handleSearch">筛选产品</el-button>
                </el-input>
              </el-col>
            </el-row>
          </div>
        </el-row>

      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        :default-sort="{prop: 'name', order: 'descending'}"
        style="width: 100%"
        @sort-change="handleSort"
        @selection-change="handleSelectionChange"
      >

        <el-table-column
          type="selection"
          width="55"
        />

        <el-table-column align="center" width="120" prop="id" label="id">
          <template slot-scope="scope">
            <div><a
              :href="'https://www.google.com/searchbyimage?site=search&sa=X&image_url='+scope.row.image"
              target="_blank"
            >Google</a></div>
            <div><a :href="scope.row.url" target="_blank">原链接</a></div>
            {{ scope.row.id }}
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          fixed
          label="图片"
          width="300"
        >
          <template slot-scope="scope">
            <el-row>
              <el-col :span="12">
                <el-image :title="scope.row.image" :preview-src-list="scope.row.images" :src="scope.row.image" width="100" style="width: 100px;" />
                <!--                <el-tooltip class="item" effect="light" placement="top-start">-->
                <!--                  <div slot="content"><img :src="scope.row.image" width="320"><span style="display: block">{{scope.row.image}}</span></div>-->
                <!--                  <img @click="handleViewCrawlProductImage(scope.row)" :src="scope.row.image" width="90">-->
                <!--                </el-tooltip>-->
              </el-col>
              <el-col :span="12">
                <el-tag v-if="scope.row.removedbg" type="success">图片已去水印</el-tag>
                <el-button
                  size="mini"
                  type="warning"
                  @click="handleModifyProduct(scope.row)"
                >编辑本地产品
                </el-button>
                <el-tag v-if="!scope.row.change_price" type="danger">价格已修改:{{ scope.row.modify_price }}</el-tag>
              </el-col>
            </el-row>
            <el-row>
              <span>{{ scope.row.create_at }}</span>
              <el-radio-group v-model="scope.row.product_type" size="mini" @change="handleUpdateWebitems(scope.row)">
                <el-radio-button label="ignore" />
                <el-radio-button label="hold" />
                <el-radio-button label="modified" />
              </el-radio-group>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="100"
          label="销售情况"
        >
          <template slot-scope="scope">
            <small>销量:<span style="color: blue">{{ scope.row.sales }}</span></small>
            <br>
            <small>reviews<span style="color: red">{{ scope.row.reviews }}</span></small>
            <br>
            <small>评分:<span style="color: red">{{ scope.row.review_star }}</span></small>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          width="150"
          label="价格"
        >
          <template slot-scope="scope">
            <small>原价:<span style="color: blue">{{ scope.row.price.toFixed(2) }}</span></small>
            <br>
            <small>预估售价<span style="color: red">{{ scope.row.cacul_price.toFixed(2) }}</span></small>
            <br>
            <small>预估毛利:<span style="color: red">{{ scope.row.profit.toFixed(2) }}</span></small>
            <br>
            <small>占比:<span style="color: red">{{ scope.row.profit_p }}%</span></small>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="name"
        >
          <template slot-scope="scope">
            <el-popover
              placement="top-start"
              title="meta信息"
              width="600"
              trigger="click"
            >
              <div>[name]{{ scope.row.name }}</div>
              <hr>
              <div>[meta_title]{{ scope.row.meta_title }}</div>
              <hr>
              <div>[meat_desc]{{ scope.row.meta_description }}</div>
              <hr>
              <div>[url]{{ scope.row.url }}</div>

              <span slot="reference">{{ scope.row.name }}
                <br>
                <el-tag v-if="scope.row.search_keyword" type="success">{{ scope.row.search_keyword }}</el-tag>
                <el-tag v-if="scope.row.category_name" type="danger">{{ scope.row.category_name }}</el-tag>
              </span>

            </el-popover>

          </template>
        </el-table-column>
        <el-table-column align="center" width="250" prop="upload_count" label="已经上传">
          <template slot-scope="scope">
            <small v-for="(item,index) in scope.row.uploaded_webs" :key="index" style="display: block"><a target="_blank" :href="item.target_url">{{ item.domain }}:{{ item.ps_product }}</a></small>
          </template>
        </el-table-column>
      </el-table>
      <div style="float:left">
        <el-button type="success" size="mini" icon="el-icon-search" @click="handleSearch">刷新</el-button>
        <el-button v-if="this.multipleSelection.length > 0" type="warning" size="mini" @click="handleDeleteSelected()">删除选择</el-button>
        <!--<el-button type="danger" @click="handleDeleteAll()">删除所有</el-button>-->
      </div>

      <el-pagination
        v-if="tableData.length"
        background
        class="mt-pagination"
        :current-page="page"
        :page-sizes="[10,20,50,100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </el-dialog>
    <crawlimage
      :product_id="target_id"
      :titlename="crawlimage_dialog_title"
      :image-dialog-visible="crawlimage_visualbe"
      @closeDialog="crawlimage_visualbe=false"
    />
    <choosecategory
      :website_id="direct_upload_web_id"
      :choosedialog-visible="direct_upload_dialogVisible"
      :default_catalog="direct_upload_default_category"
      :default-checked-keys="direct_upload_associated_categories"
      @SetChoose="handleSetDirectUploadCategories"
      @closeDialog="direct_upload_dialogVisible=false"
    />
    <prestaproduct
      :domain="operate_domain"
      :product_id="operate_product_id"
      :local_id="operate_local_id"
      :pst-visible="remoteModifydialogVisible"
      @closePstDialog="handlePstClose"
    />
  </div>
</template>

<script>
import {
  GetWebItems,
  UpdateWebItems,
  direct_add_item_to_task,
  batch_item_remove_bg,
  DeleteWebItems
} from '@/api/erp/crawlproduct'
import { CatalogTree as GetWebsiteCatalogs, Get as GetWebsite } from '@/api/erp/elicink/website'
import Choosecategory from '@/views/prestashop/element/choosecategory'
import crawlimage from '@/views/crawl/elements/crawlimage'
import qs from 'qs'
import Prestaproduct from '../../prestashop/element/prestaproduct'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Uploadbykeyword',
  components: { Prestaproduct, crawlimage, Choosecategory },
  props: ['uploadVisible', 'keyword', 'keyword_id', 'source_web_id', 'keyword_target_web_id'],
  data() {
    return {
      operate_domain: '',
      operate_product_id: '',
      item: {},
      operate_local_id: '',
      remoteModifydialogVisible: false,
      direct_upload_state: 'warning',
      direct_upload_dialogVisible: false,
      direct_upload_associated_categories: [],
      direct_upload_default_category: 2,
      multipleSelection: [],
      uploadedonly: 'all',
      min_orders: '',
      min_price: '',
      max_price: '',
      min_reviews: '',
      min_star: '',
      product_type: '',
      product_types: [
        {
          value: '',
          label: '未处理'
        },
        {
          value: 'hold',
          label: '待修改'
        },
        {
          value: 'modified',
          label: '已修改'
        },
        {
          value: 'ignore',
          label: '忽略'
        },
        {
          value: 'uploaded',
          label: '已添加上传'
        }
      ],
      uploadedonlyoptions: [
        {
          value: 'all',
          label: '所有'
        },
        {
          value: 'uploaded',
          label: '已经上传'
        },
        {
          value: 'unupload',
          label: '目标网站未上传'
        },
        {
          value: 'newtoall',
          label: '所有网站未上传'
        }
      ],
      direct_upload_able: false,
      direct_upload_web_id: '',
      dialogVisible: false,
      websites: [],
      categoryDialogLoading: false,
      loading: true,
      tableData: [],
      target_id: -1,
      review_target_url: '',
      review_visualbe: false,
      crawlimage_visualbe: false,
      crawlimage_dialog_title: '图片管理',
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0
    }
  },
  watch: {
    uploadVisible(v) {
      this.dialogVisible = v
      if (v) {
        this.getList()
      }
    },
    keyword_target_web_id(v) {
      this.direct_upload_web_id = v
    }
  },
  created() {
    GetWebsite().then(response => {
      this.websites = response.data.data
    })
  },
  methods: {
    handleSelectionChange(val) {
      if (val.length > 0) {
        this.multipleSelection = val.map(m => m.id)
      }
    },
    handleUpdateWebitems(row) {
      UpdateWebItems(row).then(resonse => {
        this.$message.success('修改成功')
        const index = this.tableData.findIndex(item => item.id === row.id)
        this.tableData.splice(index, 1)
      }).catch(e => {
        this.$message.error('修改失败')
      })
    },
    handleBatchRemoveBg() {
      batch_item_remove_bg(JSON.stringify({
        pks: this.multipleSelection,
        target_web_id: this.direct_upload_web_id
      })).then(resonse => {
        this.loading = false
        this.$notify({
          title: '成功',
          message: resonse.message,
          type: 'success',
          duration: 4500
        })
        this.getList()
      }).catch(e => {
        this.loading = false
      })
    },
    handleClickDirectUpload(v) {
      this.loading = true
      direct_add_item_to_task(JSON.stringify({
        pks: this.multipleSelection,
        newtoall: this.newtoall,
        associated_categories: this.direct_upload_associated_categories,
        default_category: this.direct_upload_default_category,
        target_web_id: this.direct_upload_web_id
      })).then(resonse => {
        this.loading = false
        this.$notify({
          title: '成功',
          message: resonse.message,
          type: 'success',
          duration: 4500
        })
        this.getList()
      }).catch(e => {
        this.loading = false
      })
    },
    handleClickDirectUploadAll() {
      this.$prompt('请输入(1-5000)的数值', '批量上传的产品数量', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: 4800,
        inputErrorMessage: '请输入数字'
      }).then(({ value }) => {
        this.loading = true
        direct_add_item_to_task(JSON.stringify({
          pks: [],
          newtoall: this.newtoall,
          max_count: value,
          web: this.source_web_id,
          associated_categories: this.direct_upload_associated_categories,
          default_category: this.direct_upload_default_category,
          min_orders: this.min_orders,
          min_price: this.min_price,
          max_price: this.max_price,
          min_reviews: this.min_reviews,
          min_star: this.min_star,
          crawl_keyword: this.keyword_id,
          target_web_id: this.direct_upload_web_id

        })).then(resonse => {
          this.loading = false
          this.$notify({
            title: '成功',
            message: resonse.message,
            type: 'success',
            duration: 4500
          })
          this.$emit('uploadsuccess', this.keyword_id)
        }).catch(e => {
          this.loading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    handleCHooseDirectuploadCategory() {
      this.direct_upload_dialogVisible = true
    },
    handleSetDirectUploadCategories(v) {
      this.direct_upload_default_category = v.default_catalog
      this.direct_upload_associated_categories = v.target_catalogs
      if (this.direct_upload_associated_categories.length === 0) {
        this.direct_upload_state = 'warning'
      } else {
        this.direct_upload_state = 'success'
      }
    },
    handleDirectUPloadChange() {
      if (this.uploadedonly) {
        this.getList()
      }
    },
    resetTemp() {
      this.temp = {
        name: '',
        url: ''
      }
    },
    getList() {
      this.loading = true
      // 清空数据,容易导致失败
      this.total = 0
      this.tableData = []
      GetWebItems(qs.stringify({
        web: this.source_web_id,
        category: '',
        product_type: this.product_type,
        min_orders: this.min_orders,
        min_price: this.min_price,
        max_price: this.max_price,
        min_reviews: this.min_reviews,
        min_star: this.min_star,
        crawl_keyword: this.keyword_id,
        kw: this.kwInput,
        order_by: this.order_by,
        order_desc: this.order_desc,
        pagesize: this.pagesize,
        newtoall: this.newtoall,
        uploadedonly: this.uploadedonly,
        upload_web_id: this.direct_upload_web_id,
        page: this.page
      }))
        .then(response => {
          this.tableData = response.data.data
          this.loading = false
          this.multipleSelection = []
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.page = 1
          this.total = 0
          this.tableData = []
          this.loading = false
        })
    },
    handleViewCrawlProductImage(row) {
      this.target_id = row.id
      this.crawlimage_dialog_title = row.name + '-图片管理'
      this.crawlimage_visualbe = true
    },
    handleModifyProduct(row) {
      this.item = row
      this.operate_local_id = row.id
      this.operate_product_id = ''
      this.operate_domain = ''
      this.remoteModifydialogVisible = true
    },
    handlePstClose(v) {
      this.remoteModifydialogVisible = false
      this.item.change_price = v.change_price
      if (v.modified) {
        this.item.product_type = 'modified'
        const index = this.tableData.findIndex(item => item.id === v.id)
        this.tableData.splice(index, 1)
      }
    },
    handleFetchWebsiteCatalogs() {
      this.categoryDialogLoading = true
      GetWebsiteCatalogs(this.uploadTargetWebsite.id).then(respone => {
        this.catalogs = respone.data
        this.categoryDialogLoading = false
      }).catch(e => {
        this.categoryDialogLoading = false
      })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // 删除选择的产品
    handleDeleteSelected() {
      if (!confirm('产品删除以后所有跟产品相关的记录都会删除,确定要删除吗？')) {
        return
      }
      DeleteWebItems(null, { 'ids': this.multipleSelection }).then((response) => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      }).catch(error => {
        console.log(error)
      })
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeUploadByKeywordDialog', false)
    }
  }
}
</script>

<style scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  /*.top >>> .el-select .el-input {*/
  /*  width: 350px;*/
  /*}*/

  .top >>> .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .top {
    padding-left: 20px;
    margin-bottom: 30px;
    margin-top: 28px;
  }

  .input-with-select {
    width: calc(100% - 200px);
  }

  .add-btn {
    float: right;
    margin-right: 20px;
    width: 150px
  }

  .mt-pagination {
    float: right;
    margin-top: 5px;
  }

  .app-container >>> .el-dialog {
    margin-top: 48px !important;
    margin-bottom: 68px;
  }

  .mt-dialog >>> .el-transfer-panel {
    width: calc(50% - 60px);
  }

  .mt-form >>> .el-select {
    width: 100%;
  }

  .mt-form >>> .el-input__inner {
    width: 100%;
  }

  .mt-dialog >>> .el-dialog {
    margin: 168px auto !important;
  }

  .mt-dialog >>> .el-dialog__body {
    padding-bottom: 100px;
  }

  .mt-dialog >>> .el-dialog {
    margin: 10px auto !important;
  }
</style>
